export class infiniteScroll {
  constructor(vm) {
    this.vm = vm
    this.dropdown = null
    this.isScrollHandlerAdded = false
  }

  manageScrollHandler(action, ele) {
    this.vm.$nextTick(() => {
      this.dropdown = document.querySelector(ele)
      if (!this.dropdown) return
      if (action === 'add') {
        if (!this.isScrollHandlerAdded) {
          this.dropdown.addEventListener('scroll', this.scrollHandle.bind(this))
          this.isScrollHandlerAdded = true
        }
      } else if (action === 'remove') {
        if (this.isScrollHandlerAdded) {
          this.dropdown.removeEventListener('scroll', this.scrollHandle.bind(this))
          this.isScrollHandlerAdded = false
        }
      }
    })
  }

  scrollHandle() {
    if (!this.dropdown) return
    const { scrollTop, scrollHeight, clientHeight } = this.dropdown
    // 判断是否滚动到底部
    if (scrollTop + clientHeight >= scrollHeight - 10 && this.vm.store.status !== 1) {
      this.vm.store.page += 1
      this.vm.loadData({ page: this.vm.store.page })
      this.vm.options = [...this.vm.options, ...this.vm.store.data]
    }
  }
}
